package deepcopy;

import java.io.*;

public class CopyOneTest {

    /**
     * 输入输出是相对于程序而言
     * @param t
     * @param <T>
     * @return
     */
    public static <T extends Serializable> T clone(T t) {
        T cloneObj = null;
        try {
            // 将对象写入字节流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(t);
            oos.close();
            // 从字节流中读取
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            cloneObj = (T) ois.readObject();
            ois.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return cloneObj;
    }

    public static void main(String[] args) {
        // 深拷贝
        Teacher teacher = new Teacher("fang",26);
        Teacher clone = clone(teacher);
        clone.setName("wang");
        System.out.println(teacher);
        System.out.println(clone);
        System.out.println("---------------------------------------");
        // 浅拷贝
        Teacher teacher1 = teacher;
        teacher1.setName("hhhhh");
        System.out.println(teacher1);
        System.out.println(teacher);
    }
}
